package com.globallogic.strelchuk.usermanager.dao;

import java.util.List;

import com.globallogic.strelchuk.usermanager.domain.Activity;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class ActivityDaoImpl implements ActivityDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Transactional
	public void addActivity(Activity activity) {
		sessionFactory.getCurrentSession().save(activity);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Activity> listAllActivities(Integer userId) {
		return sessionFactory.getCurrentSession()
				.createQuery("from Activity where userId=?")
				.setParameter(0, userId).list();
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Activity> listNotDoneActivities(Integer userId) {
		return sessionFactory.getCurrentSession()
				.createQuery("from Activity where done=0 and userId=?")
				.setParameter(0, userId).list();
	}

	@Transactional
	public void removeActivity(Integer id) {
		Activity activity = (Activity) sessionFactory.getCurrentSession().load(
				Activity.class, id);
		if (null != activity) {
			sessionFactory.getCurrentSession().delete(activity);
		}
	}

	@Transactional
	public void markActivityDone(Integer id) {
		Activity activity = (Activity) sessionFactory.getCurrentSession().load(
				Activity.class, id);
		if (null != activity) {
			activity.setDone(1);
			sessionFactory.getCurrentSession().update(activity);
		}
	}

	@Transactional
	public void markActivityUndone(Integer id) {
		Activity activity = (Activity) sessionFactory.getCurrentSession().load(
				Activity.class, id);
		if (null != activity) {
			activity.setDone(0);
			sessionFactory.getCurrentSession().update(activity);
		}
	}

	@Transactional
	public void setEditable(Integer id, boolean editable) {
		Activity activity = (Activity) sessionFactory.getCurrentSession().load(
				Activity.class, id);
		if (null != activity) {
			activity.setEditable(editable);
			sessionFactory.getCurrentSession().update(activity);
		}
	}

	@Transactional
	public void editActivity(Activity activity, Integer id) {

		Activity act = (Activity) sessionFactory.getCurrentSession().load(
				Activity.class, id);
		if (null != act) {
			act.setName(activity.getName());
			act.setCreateDate(activity.getCreateDate());
			act.setStartDate(activity.getStartDate());
			act.setDueDate(activity.getDueDate());
			act.setEditable(activity.isEditable());

			sessionFactory.getCurrentSession().update(act);
		}
	}

	@Transactional
	public Activity getActivityById(Integer id) {
		return (Activity) sessionFactory.getCurrentSession()
				.createQuery("from Activity where id=?").setParameter(0, id)
				.list().get(0);
	}
}
